<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 22:34
 * 资金
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Commission;
use app\common\model\RedEnvelope;
use app\common\model\Withdraw;
use app\common\model\WithdrawAccount;
use think\Db;

class Funds extends Api {
	
	/**
	 * 资金记录
	 */
	public function index(){
		$userId = $this->auth->id;
		$model = new \app\common\model\Funds();
		$where['f.user_id'] = $userId;
		$operation_type = $this->request->post('operation_type');
		$operation_type && $where['f.operation_type'] = $operation_type;
		
		$type = $this->request->post('type');
		$type && $where['f.type'] = $type;
		
		$page = $this->request->post('page', 1, 'intval');
		$count = $model->alias('f')->where($where)->count();
		$list = Db::name('funds')->alias('f')
			->join('order o', 'f.order_id = o.id', 'left')
			->join('user u', 'f.relation_user_id = u.id', 'left')
			->join('promotion p', 'f.relation_user_id = p.user_id', 'left')
			->join('agentShop a', 'f.relation_user_id = a.user_id', 'left')
			->where($where)
			->page($page)
			->field('f.id, f.amount, f.type, from_unixtime(f.create_time, "%Y-%m-%d") as date, u.nickname, p.name as promotion_name, a.name as agent_name, o.user_id as order_user_id, f.relation_user_id')
			->order(['f.create_time' => 'desc'])
			->select();
		
		if($list) {
			$typeList = \app\common\model\Funds::$typeList;
			foreach ($list as &$item) {
				$item['type_text'] = $typeList[$item['type']];
				$item['relation_name'] = $item['order_user_id'] == $item['relation_user_id'] ? '用户:'.$item['nickname'] : ($item['agent_name'] ? '代言人：'.$item['agent_name'] : '下级：'.$item['promotion_name']);
			}
		}
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list
		]);
	}
	
	/**
	 * 佣金
	 */
	public function commission(){
		$userId = $this->auth->id;
		$model = new Commission();
		$where['user_id'] = $userId;
		
		$type = $this->request->post('type', 1, 'intval');
		if($type == 1) {
			$where['type'] = ['in', [Commission::TYPE_SALE, Commission::TYPE_RECOMMEND]];
		} else {
			
			$where['type'] = $type;
		}
		
		$page = $this->request->post('page', 1, 'intval');
		$count = $model->where($where)->count();
		$list = $model->where($where)
			->page($page)
			->order(['create_time' => 'desc'])
			->field('id, from_unixtime(create_time, \'%y/%m/%d\') as date, amount, type, status')
			->select();
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list
		]);
	}
	
	
	/**
	 * 提现规则
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function withdrawRule() {
		$rule = Db::name('withdrawRule')->find();
		$this->success('查询成功', $rule);
	}
	
	/**
	 * 提现
	 */
	public function withdraw() {
		$accountId = $this->request->post('account_id');
		!$accountId && $this->error('请选择收款帐号');
		
		
		
		$amount = $this->request->post('amount');
		!$amount && $this->error('请输入提现金额');
		
		$rule = Db::name('withdrawRule')->find();
		
		if($amount < $rule['min_amount']) {
			$this->error('最低提现'.$rule['min_amount']).'元';
		}
		
		if($rule['max_amount'] > 0 && $amount > $rule['max_amount']) {
			$this->error('单笔最多提现'.$rule['max_amount'].'元');
		}
		
		
		
		$userId = $this->auth->id;
		$account = Db::name('withdrawAccount')->alias('a')
			->join('bank b', 'a.bank_id = b.id', 'left')
			->where(['a.id' => $accountId, 'a.user_id' => $userId])
			->field('b.name as bankName, a.account_name, a.account_no, a.bank_address')
			->find();
		
		!$account && $this->error('收款帐号不存在');
		
		
		$user = \app\admin\model\User::get($userId);
		if($user['money'] < $amount) {
			$this->error('余额不足');
		}
		
		$fee = $amount*$rule['tax'] + $rule['fee'];
		
		if($fee > $amount) {
			$this->error('最少提现'.$fee.'元');
		}
		$model = new Withdraw();
		$res = $model->withdraw($user, $amount, $fee , $account['bankName'], $account['account_name'], $account['account_no'], $account['bank_address']);
		if($res) {
			$this->success('提交成功，等待转帐');
		} else {
			$this->error($model->getError());
		}
	}
	
	/**
	 * 提现记录
	 */
	public function withdrawRecord() {
		$userId = $this->auth->id;
		$model = new Withdraw();
		$where['user_id'] = $userId;
		
		
		$page = $this->request->post('page', 1, 'intval');
		$count = $model->where($where)->count();
		$list = $model->where($where)
			->page($page)
			->order(['create_time' => 'desc'])
			->field('*, from_unixtime(create_time, "%Y-%m-%d") as date')
			->select();
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list
		]);
	}
	
	
	/**
	 * 红包记录
	 */
	public function hb() {
		$userId = $this->auth->id;
		$model = new RedEnvelope();
		$where['user_id'] = $userId;
		
		
		$page = $this->request->post('page', 1, 'intval');
		$count = $model->where($where)->count();
		$list = $model->where($where)
			->page($page)
			->order(['create_time' => 'desc'])
			->field('*, from_unixtime(create_time, "%Y-%m-%d") as date')
			->select();
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list
		]);
	}
	
	
	/**
	 * 我的提现帐号
	 * @param token 用户token
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function account(){
		$id = $this->auth->id;
		
		$rows = Db::name('withdrawAccount')->alias('a')
			->join('bank b', 'a.bank_id = b.id', 'left')
			->where(['a.user_id' => $id, 'a.status' => 1])
			->field('a.id, a.account_no, a.account_name, b.name, b.logo_image, a.bank_address')
			->order(['a.create_time' => 'desc'])
			->select();
		$this->success('查询成功', $rows);
	}
	
	
	/**
	 * @param token 用户token
	 * @param bank_id 收款帐号类型ID
	 * @param account_no 收款帐号
	 * @param account_name 收款人
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addAccount(){
		$userId = $this->auth->id;
		$bankId = input('post.bank_id','', 'int');
		$accountNo = input('post.account_no');
		$accountName = input('post.account_name');
		
		if(!$bankId || !$accountNo || !$accountName) {
			$this->error('参数错误');
		}
		
		$bank = Db::name('bank')->find($bankId);
		if(!$bank){
			$this->error('收款帐号类型不存在');
		}
		
		$bank_address = input('post.bank_address');
		
		$model = new WithdrawAccount();
		$res = $model->isUpdate(false)->save([
			'user_id' => $userId,
			'bank_id' => $bankId,
			'account_no' => $accountNo,
			'account_name' => $accountName,
			'bank_address' => $bank_address
		]);
		
		if($res) {
			$this->success('添加成功');
		} else{
			$this->error('添加出错，请稍候重试');
		}
	}
	
	
	/**
	 * 删除收款帐号
	 * @param token 用户token
	 * @param id 收款帐号ID
	 */
	public function delAccount(){
		$userId = $this->auth->id;
		$id = input('post.id', '', 'int');
		
		$model = new WithdrawAccount();
		$res = $model->save(['status' => 0],['user_id' => $userId, 'id' => $id]);
		if($res !== false) {
			$this->success('删除成功');
		}
		
		$this->error('删除出错，请稍候重试');
	}
	
	
	/**
	 * 银行列表
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function banks()
	{
		$banks = Db::name('bank')
			->where(['status' => 1])
			->field('id, name, logo_image')
			->order(['sort' => 'ASC'])
			->select();
		$this->success('查询成功', $banks);
	}
}
